package org.ethan.lyl.controller;

import org.apache.logging.log4j.util.Strings;
import org.ethan.lyl.Screenshot;
import org.ethan.lyl.util.Path;
import org.ethan.lyl.util.ResultDto;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

/**
 * @Author:Eason Lau
 * @Date:2018/10/31
 * @Description:
 */
@RestController
@RequestMapping("devices")
public class DeviceController {
    @RequestMapping("list")
    public ResultDto getDeviceList(){
        String path = Path.SysPath();
        File adbDir = new File(path+ "adb");
        String cmd = "cmd.exe /c " + adbDir + "/adb" + " devices";
        System.out.println(cmd);
        System.out.println(path);
        Runtime runtime = Runtime.getRuntime();
        try {

            Process p = runtime.exec(cmd);
            p.waitFor();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
            String line=null;
            StringBuffer b=new StringBuffer();
            while ((line=br.readLine())!=null) {
                b.append(line+"\n");
            }
            System.out.println(b.toString());

            //System.out.println(b.toString());
            String deviceCode = b.toString().replace("List of devices attached","").replace("\tdevice","").trim();
            if(Strings.isNotBlank(deviceCode)){
                return ResultDto.success("设备已连接",deviceCode);
            }
            else
            {
                return ResultDto.fail("设备未连接");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultDto.success();
    }
}
